/*===============================================
	File:		BitmapFont.cpp					||
	Course:		SGD 1208						||
	Author:		CMorehead						||
	Purpose:	Class to handle the fonts		||
================================================*/

#include "BitmapFont.h"
#include <cassert>
#include "../source/IGraphics.h"
#include "../source/Constants.h"
#include "../source/Resources.h"
#include "../source/Geometry.h"

BitmapFont::BitmapFont(void)
{
	m_nCharWidth = 32;			//spacing of fonts
	m_nCharHeight = 32;			
	m_nNumRows = 6;				
	m_nNumCols = 10;			

	m_cFirstChar = ' ';			// '!'
	m_bOnlyUppercase = true;	// true

	nCellWidth	= 32;			//char width...
	nCellHeight	= 32;			

	rSource = new SRect();

	m_pGraphics	= IGraphics::GetInstance();
	m_hTexture			= HTexture();

	m_hTexture = m_pGraphics->LoadTexture( GRAPHICS_PATH( "TemporaryFont" ) );
	assert( m_hTexture != INVALID_HANDLE && "CBitmapFont::Enter - could not load COptionsState image" != 0 );
}

BitmapFont::~BitmapFont(void)
{
	m_pGraphics->UnloadTexture(m_hTexture);
	m_hTexture = HTexture();

	if (rSource != nullptr)
	{
		delete rSource;
		rSource = nullptr;
	}
}

SRect* BitmapFont::CellAlgorithm( int id )
{
	rSource->left		= (id % m_nNumCols) * nCellWidth;
	rSource->top		= (id / m_nNumCols) * nCellHeight;

	rSource->right	= rSource->left	+ nCellWidth;
	rSource->bottom	= rSource->top	+ nCellHeight;

	return rSource;
}

void BitmapFont::Print(const char* szText, int nX, int nY, float fScale, SColor dwColor)
{
	// Keep track of the starting x position (for newlines)
	int nColStart = nX;

	// Iterate through the string 1 character at a time
	int nLength = strlen( szText );

		for( int i = 0; i < nLength; i++ )
		{
			// Get char out of the string
			char ch = szText[ i ];


			// Check for whitespace
			if( ch == ' ' )
			{
				nX += m_nCharWidth * fScale;
				continue;
			}
			else if( ch == '\n' )
			{
				nX = nColStart;
				nY += m_nCharHeight * fScale;
				continue;
			}

			// Convert to uppercase?
			if( m_bOnlyUppercase == true )
				ch = toupper( ch );

			// Calculate the tile id for this character
			int id = ch - m_cFirstChar;

			// Get the source rect using the Cell Algorithm
			SRect* rTile = CellAlgorithm( id );

			// Draw!
			//m_pTM->Draw( m_nImageID, nX, nY, fScale, fScale, &rTile, 0.0f, 0.0f, 0.0f, dwColor );
			m_pGraphics->DrawTextureSection(m_hTexture, nX, nY, rTile, 0.0f, 0.0f, 0.5f, SColor(), fScale, fScale);
			// Move to the next location on screen
			nX += m_nCharWidth * fScale;
		}
}
